package com.dsx.haha.controller;

import com.dsx.haha.model.entity.Article;
import com.dsx.haha.model.entity.Tenant;
import com.dsx.haha.model.entity.User;
import com.dsx.haha.model.vo.TenantVo;
import com.dsx.haha.service.TenantService;
import com.dsx.haha.service.UserService;
import com.dsx.haha.utils.RedPrint;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.session.HttpServletSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dsx
 * @date 2021/3/11 18:27
 * @since JDK1.8
 */
@Controller
@RequestMapping("/tenant")
public class LoginController {
    
    @Reference
    TenantService tenantService;
    @Reference
    UserService userService;
    
    //跳转到注册界面
    @RequestMapping("/toregist")
    public String toreg(){
        return "tenant/registt";
    }
    //注册租户，完成后跳转成功页面
    @PostMapping("/addtenant")
    public String reg(TenantVo vo, Model model){
        model.addAttribute("at_username2",vo.getCreateMan());
        tenantService.addTenant(vo);
        return "tenant/success" ;
    }
    //注册后跳转到登录界面
    @RequestMapping("/tologin")
    public String tologin(String username,Model model){
        model.addAttribute("tl_username",username);
        return "tenant/login";
    }
    //登陆成功界面
    @PostMapping("/login")
    public String login(String username,String password,Model model,HttpSession session){
        
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username.trim(), password.trim());
        token.setRememberMe(true);
        try {
            subject.login(token);
            session.setAttribute("username",username);
            return "redirect:/tenant/loginsucc";
        } catch (UnknownAccountException e) {
            model.addAttribute("emsg","用户名错误");
            return "tenant/login";
        }catch (IncorrectCredentialsException e) {
            model.addAttribute("tl_username",username);
            model.addAttribute("emsg", "密码错误");
            return "tenant/login";
        }
    }
    @GetMapping("/loginsucc")
    public String loginSuccess(Model model,HttpServletRequest req){
        //main.html中写了好几个页面
        //用于区分主页面还是项目页面
        Subject subject = SecurityUtils.getSubject();
        User dbuser = (User) subject.getPrincipal();
        //租户界面
        if(req.getParameter("tenant_id")==null) {
            List<Map> tenants;
            if (dbuser.getId() == "3") {
                //是管理员，可以看到所有租户
                tenants = userService.getAdminTenants(dbuser.getId());
            } else {
                //不是管理员，只能看见自己当前属于的租户
                tenants = userService.getUserTenants(dbuser.getId());
            }
            if (tenants == null) {
                return "/noTenants";
            }
            //查询租户的项目，tenant的article
            Map<String, List<Article>> artMap = new HashMap<>();
            for (Map tenant : tenants) {
                String id = (String) tenant.get("id");
                List<Article> articles = userService.getArtByTenantId(id);
                artMap.put(id, articles);
            }
            model.addAttribute("artMap", artMap);
            subject.getSession().setAttribute("tenants", tenants);
            model.addAttribute("tenants", tenants);
            model.addAttribute("username", dbuser.getUserName());
            model.addAttribute("showlogin", false);
            //判断显示哪个模块(。。。)
            model.addAttribute("showdiv", true);

            model.addAttribute("div3", true);

            
        }else {
            String aid = req.getParameter("id");
            String aname = req.getParameter("article_name");
            model.addAttribute("username", dbuser.getUserName());
            model.addAttribute("showdiv", false);
            model.addAttribute("sessionAid",aid);
            model.addAttribute("sessionAname",aname);
            subject.getSession().setAttribute("seAid",aid);
           req.setAttribute("seAname",aname);
        }
        return "tenant/main";
    }
    //restful风格
//    //'/tenant/main/'+tid+"/"+aid+"/"+aname
//    @RequestMapping("/main/{tid}/{aid}/{aname}")
//    public String toArt(@PathVariable String tid,@PathVariable String aid,@PathVariable String aname){
//        System.out.println(tid);
//        System.out.println(aid);
//        System.out.println(aname);
//        return "tenant/main";
//    }
    
    //退出
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "/tenant/login";
//        return "redirect:/tenant/tologin";
    }
    //未授权页面
    @RequestMapping("/noauth")
    public String noauth(){
        return "redirect:/noauth";
    }
    
    
}
